package com.ge.pp;

import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

public class SmoothingFilter extends ImageFilter {

	public SmoothingFilter(PicturePane p) {
		super(p);
		name = "Smoothing Filter";
		
	}

	public BufferedImage filter(BufferedImage img) throws Exception {
		
		try
		{
			BufferedImage newImg = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
		Raster inRaster = img.getRaster();		
		WritableRaster outr = newImg.getRaster();
		
		
		float[] tl = new float[3];
		float[] t = new float[3];
		float[] tr = new float[3];
		float[] l = new float[3];
		float[] c = new float[3];
		float[] r = new float[3];
		float[] bl = new float[3];
		float[] b = new float[3];
		float[] br = new float[3];
				
		float[] avg = new float[3];
		
		for(int x=1; x<outr.getWidth()-1; x++) {
			for (int y=1; y<outr.getHeight()-1; y++) {
				inRaster.getPixel(x-1, y-1, tl);
				inRaster.getPixel(x, y-1, t);
				inRaster.getPixel(x+1, y-1, tr);
				
				inRaster.getPixel(x-1, y, l);
				inRaster.getPixel(x, y, c);
				inRaster.getPixel(x+1, y, r);
				
				inRaster.getPixel(x-1, y+1, bl);
				inRaster.getPixel(x, y+1, b);
				inRaster.getPixel(x+1, y+1, br);
						
				avg[0] = (tl[0]+t[0]+tr[0] +
					      l[0]+c[0]+r[0] +
					     bl[0]+b[0]+br[0]) / 9.0f;
				
				avg[1] = (tl[1]+t[1]+tr[1] +
					      l[1]+c[1]+r[1] +
					     bl[1]+b[1]+br[1]) / 9.0f;
				
				avg[2] = (tl[2]+t[2]+tr[2] +
					      l[2]+c[2]+r[2] +
					     bl[2]+b[2]+br[2]) / 9.0f;
				
				outr.setPixel(x,y, avg);
			}
		}
		
		return newImg;
		}
		catch(Exception e)
		{
			throw e;
		}
	}
}
